const Parse = require('parse/node')

register('GoodsSpecification')

// implementation details
let stockCache = {}

function register(className) {
  loadingCache(className)
  Parse.Cloud.beforeSave(className, update)
}

function update(req, res) {
  var obj = req.object
  if (!obj.id) {
    res.success(obj)
  } else if (stockCache[obj.id]) {
    increment(obj) ? res.success(obj) : res.error('已售馨')
  } else {
    res.error('服务器启动中...')
  }
}

function increment(obj) {
  var cache = stockCache[obj.id]
  var count = obj.get('stock') || 0
  if (cache + count < 0) return false
  stockCache[obj.id] = cache + count
  obj.set('stock', cache + count)
  return true
}

function loadingCache(className) {
  return new Parse.Query(className).find().then(r => {
    for (var i = 0; i < r.length; i++) {
      let obj = r[i]
      stockCache[obj.id] = obj.get('stock')
    }
  })
}
